package com.foodorder.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.foodorder.websocket.DataSyncWebSocketHandler;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 数据同步服务
 * 支持三端数据同步机制
 */
@Service
public class DataSyncService {
    
    private static final Map<String, Object> syncData = new ConcurrentHashMap<>();
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 推送数据更新到指定角色
     */
    public void pushDataUpdate(String operation, String dataType, Object data, String targetRole) {
        try {
            Map<String, Object> message = Map.of(
                "type", "dataUpdate",
                "operation", operation,
                "dataType", dataType,
                "data", data,
                "targetRole", targetRole,
                "timestamp", System.currentTimeMillis()
            );
            
            String key = targetRole + "_" + dataType + "_latest";
            syncData.put(key, message);
            
            // 通过WebSocket推送实时数据
            DataSyncWebSocketHandler.pushDataUpdate(operation, dataType, data, targetRole);
            
            System.out.println("数据同步推送: " + targetRole + " - " + dataType + " - " + operation);
            
        } catch (Exception e) {
            System.err.println("推送数据更新失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 向指定用户推送消息
     */
    public void pushToUser(String userId, String role, Object data) {
        try {
            Map<String, Object> message = Map.of(
                "type", "notification",
                "userId", userId,
                "role", role,
                "data", data,
                "timestamp", System.currentTimeMillis()
            );
            
            String key = role + "_" + userId + "_notification";
            syncData.put(key, message);
            
            // 通过WebSocket推送用户通知
            DataSyncWebSocketHandler.pushToUser(userId, role, data);
            
            System.out.println("用户消息推送: " + role + "_" + userId);
            
        } catch (Exception e) {
            System.err.println("推送用户消息失败：" + e.getMessage());
        }
    }
    
    /**
     * 广播消息给所有用户
     */
    public void broadcast(Object data) {
        try {
            Map<String, Object> message = Map.of(
                "type", "broadcast",
                "data", data,
                "timestamp", System.currentTimeMillis()
            );
            
            syncData.put("broadcast_latest", message);
            
            // 通过WebSocket广播消息
            DataSyncWebSocketHandler.broadcast(data);
            
            System.out.println("广播消息: " + data);
            
        } catch (Exception e) {
            System.err.println("广播消息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取最新同步数据
     */
    public Object getLatestSyncData(String role, String dataType) {
        String key = role + "_" + dataType + "_latest";
        return syncData.get(key);
    }
    
    /**
     * 获取用户通知
     */
    public Object getUserNotification(String userId, String role) {
        String key = role + "_" + userId + "_notification";
        return syncData.get(key);
    }
    
    /**
     * 获取广播消息
     */
    public Object getBroadcastMessage() {
        return syncData.get("broadcast_latest");
    }
    
    /**
     * 清除过期的同步数据
     */
    public void cleanExpiredData() {
        long currentTime = System.currentTimeMillis();
        long expireTime = 24 * 60 * 60 * 1000; // 24小时过期
        
        syncData.entrySet().removeIf(entry -> {
            try {
                if (entry.getValue() instanceof Map) {
                    Map<String, Object> data = (Map<String, Object>) entry.getValue();
                    Long timestamp = (Long) data.get("timestamp");
                    return timestamp != null && (currentTime - timestamp) > expireTime;
                }
            } catch (Exception e) {
                // 如果解析失败，删除这个条目
                return true;
            }
            return false;
        });
    }
    
    /**
     * 获取同步统计信息
     */
    public Map<String, Object> getSyncStats() {
        return Map.of(
            "totalSyncData", syncData.size(),
            "timestamp", System.currentTimeMillis()
        );
    }
} 